/*
 * UserService.java
 *
 * Created on 2007年4月29日, 下午9:59
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package cn.geckos.forum.service;

import java.util.List;

import jeffxu.dao.ICRUDService;
import jeffxu.dao.IBasicDao;
import jeffxu.dao.Query;
import cn.geckos.forum.domainobject.User;

/**
 *
 * @author jeff
 */
public class UserService implements ICRUDService<User>{
    
    protected IBasicDao<User> dao;
    
    public void setDao(IBasicDao dao)
    {
        this.dao = dao;
    }
    
    public boolean add(User user)
    {
        if(this.findByName(user.getName()) == null)
        {
            try
            {
                this.dao.create(user);
            }catch(Exception e)
            {
                return false;
            }
            return true;
        }else
        {
            return false;
        }
    }
    
    public boolean delete(User user)
    {
        return this.delete(user, false);
    }
    
    public boolean delete(User user, boolean permanent)
    {
        if(permanent)
        {
            try
            {
                this.dao.delete(user);
            }catch(Exception e)
            {
                return false;
            }
            return true;
        }else
        {
            user.setEnabled(User.DISABLED);
            return this.update(user);
        }
    }
    
    public User findById(long id)
    {
        Query q = new Query();
        q.setWhere("id="+id);
        try
        {
            List<User> l = this.dao.find(q);
            if(l != null) 
                return l.get(0);
            else
                return null;
        }catch(Exception e)
        {
            return null;
        }
    }
    
    public User findByName(String name)
    {
        Query q = new Query();
        q.setWhere("name="+name);
        try
        {
            List<User> l = this.dao.find(q);
            if(l != null) 
                return l.get(0);
            else
                return null;
        }catch(Exception e)
        {
            return null;
        }
    }
    
    public boolean update(User user)
    {
        try
        {
            this.dao.update(user);
        }catch(Exception e)
        {
            return false;
        }
        return true;
    }
    
}
